package com.xzq.erp.ai.history;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.xzq.erp.ai.constants.ChatConstants;
import com.xzq.erp.ai.dto.Msg;
import com.xzq.erp.ai.vo.MessageHistoryVO;
import com.xzq.erp.constants.RedisConstants;
import com.xzq.erp.enums.ResponseCodeEnum;
import com.xzq.erp.exception.BizException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 基于Redis的会话历史记录
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RedisChatHistory implements ChatHistoryRepository{

    private final RedisTemplate<String,String> redisTemplate;

    private final ObjectMapper objectMapper;

    @Override
    public void save(Long userId, String chatId) {
        log.info("保存会话: {}", chatId);
        String key = RedisConstants.buildChatHistoryKey(userId);
        Long size = redisTemplate.opsForZSet().size(key);
        if(Objects.isNull(size) || size >= ChatConstants.MAX_CHAT_HISTORY_COUNT){
            throw new BizException(ResponseCodeEnum.CHAT_HISTORY_EXCEED);
        }
        // 按用户ID保存会话ID 最近创建的会话ID 优先级最高
        redisTemplate.opsForZSet().add(key,chatId,System.currentTimeMillis());
    }

    @Override
    public List<MessageHistoryVO> getChatIds(Long userId) {
        log.info("获取用户: {} 的会话列表", userId);
        // 获取用户ID对应的会话ID列表
        Set<String> chatIds = redisTemplate.opsForZSet().reverseRange(RedisConstants.buildChatHistoryKey(userId), 0, -1);
        if( chatIds == null ||  chatIds.isEmpty()){
             return List.of();
        }
        // 根据会话ID获取会话信息
        List<String> keys = chatIds.stream().map(RedisConstants::buildChatMemoryKey).toList();
        Map<String,String> chatHistory = Maps.newHashMap();
        for(String key: keys){
            String json = redisTemplate.opsForList().index(key, 1);
            try {
                Msg msg = objectMapper.readValue(json, Msg.class);
                chatHistory.put(key,msg.getText());
            } catch (IOException e) {
                log.error("解析会话信息失败: {}", e.getMessage());
            }
        }
        List<MessageHistoryVO> vos = new ArrayList<>(chatIds.size());
        for(String chatId: chatIds){
            MessageHistoryVO vo = new MessageHistoryVO(chatId,chatHistory.getOrDefault(RedisConstants.buildChatMemoryKey(chatId),null));
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public void delete(Long userId, String chatId) {
        log.info("删除会话: {}", chatId);
        String historyKey = RedisConstants.buildChatHistoryKey(userId);
        // 删除用户历史会话ID
        redisTemplate.opsForZSet().remove(historyKey, chatId);
    }
}
